/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.xxl.adapter.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.xxl.adapter.core.XxlConvert;
import com.xxl.adapter.entity.JobLogGlue;
import com.xxl.adapter.repository.JobLogGlueRepository;
import com.xxl.job.admin.core.model.XxlJobLogGlue;
import com.xxl.job.admin.dao.XxlJobLogGlueDao;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.criteria.CriteriaBuilder.In;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.criteria.internal.OrderImpl;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Component;

/**
 * XxlJobLogGlueDaoImpl
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class JobLogGlueDaoImpl implements XxlJobLogGlueDao, XxlConvert {

  @Autowired private JobLogGlueRepository repository;

  @Override
  public int save(XxlJobLogGlue xxlJobLogGlue) {
    JobLogGlue jobLogGlue = repository.save(this.convert(JobLogGlue.class, xxlJobLogGlue));
    xxlJobLogGlue.setId(jobLogGlue.getId());
    return jobLogGlue.getId();
  }

  @Override
  public List<XxlJobLogGlue> findByJobId(int jobId) {
    return this.convert(
        XxlJobLogGlue.class,
        repository.findAll(
            ((root, query, cb) -> cb.equal(root.get("jobId"), jobId)), Sort.by(Order.desc("id"))));
  }

  @Override
  public int removeOld(int jobId, int limit) {
    List<Integer> ids =
        repository
            .findAll(
                ((root, query, criteriaBuilder) -> {
                  query.orderBy(new OrderImpl(root.get("updateTime"), false));
                  return criteriaBuilder.equal(root.get("jobId"), jobId);
                }),
                PageRequest.of(0, limit))
            .get()
            .map(JobLogGlue::getId)
            .collect(Collectors.toList());

    List<JobLogGlue> list =
        repository.findAll(
            (root, query, cb) -> {
              In<Integer> in = cb.in(root.get("id"));
              ids.forEach(in::value);
              return cb.and(cb.not(in), cb.equal(root.get("jobId"), jobId));
            });
    repository.deleteAllInBatch(list);

    return 1;
  }

  @Override
  public int deleteByJobId(int jobId) {
    List<JobLogGlue> list =
        repository.findAll((root, query, cb) -> cb.equal(root.get("jobId"), jobId));
    if (CollectionUtil.isNotEmpty(list)) {
      repository.deleteAllInBatch(list);
    }

    return 1;
  }

  @Override
  public Logger getLogger() {
    return log;
  }
}
